package com.czxy.changgou4.controller;

import com.aliyuncs.exceptions.ClientException;
import com.czxy.changgou4.pojo.User;
import com.czxy.changgou4.utils.SmsUtil;
import com.czxy.changgou4.vo.BaseResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping
    public BaseResult sendSms(@RequestBody User user) {
        try {
            //1 获得4长度随机数字字符串
            String randomNumber = RandomStringUtils.randomNumeric(4);

            //2 将随机字符串存放到redis中 , key格式： sms_register手机号
            String key = "sms_register" + user.getMobile();
            stringRedisTemplate.opsForValue().set(key,randomNumber,5, TimeUnit.MINUTES);

            //3 发送短信
//            SmsUtil.sendSms(user.getMobile(), user.getUsername(),randomNumber,"","");

            System.out.println("短信验证码：" + randomNumber);

            return BaseResult.ok("短信发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error("短信发送失败");
        }
    }

    public static void main(String[] args) {
        System.out.println(RandomStringUtils.randomNumeric(4));
    }
}
